package com.jzr.bedside.ui.voip

import android.content.Intent
import android.view.View
import com.blankj.utilcode.utils.ToastUtils
import com.jzr.bedside.R
import com.jzr.bedside.base.BaseActivity
import com.jzr.bedside.utils.rtc.AEvent
import com.jzr.bedside.utils.rtc.IEventListener
import com.starrtc.starrtcsdk.api.XHClient
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback
import kotlinx.android.synthetic.main.activity_voip_ringing.*

class VoipRingingActivity : BaseActivity(), IEventListener, View.OnClickListener {


    private var targetId: String? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_voip_ringing
    }

    override fun attachView() {

    }

    override fun detachView() {

    }

    override fun initView() {

        ring_hangoff.setOnClickListener(this)
        ring_pickup.setOnClickListener(this)
        addListener()

        targetId = intent.getStringExtra("targetId")


    }


    fun addListener() {
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_HANGUP, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_ERROR, this)
    }

    fun removeListener() {
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_HANGUP, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_ERROR, this)
    }


    override fun dispatchEvent(aEventID: String?, success: Boolean, eventObj: Any?) {
        when (aEventID) {
            AEvent.AEVENT_VOIP_REV_HANGUP -> {
                ToastUtils.showLongToast("对方已挂断")
                finish()
            }
            AEvent.AEVENT_VOIP_REV_ERROR -> {
                finish()
            }
        }
    }


    override fun onRestart() {
        super.onRestart()
        addListener()
    }

    override fun onStop() {
        super.onStop()
        removeListener()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ring_hangoff -> {
                XHClient.getInstance().voipManager
                    .refuse(object : IXHResultCallback {
                        override fun success(data: Any?) {
                            finish()
                        }

                        override fun failed(errMsg: String?) {
                            finish()
                        }
                    })
            }
            R.id.ring_pickup->{
                val intent = Intent(this@VoipRingingActivity, VoipActivity::class.java)
                intent.putExtra("targetId", targetId)
                intent.putExtra(VoipActivity.ACTION, VoipActivity.RING)
                startActivity(intent)
                finish()
            }
        }
    }


}
